class Solution {
public:
    vector<int> s;
    bool verifySequenceOfBST(vector<int> sequence) {
        s = sequence;
        if(s.empty()) return true;
        return dfs(0,s.size() - 1);
    }
    bool dfs(int l,int r){
        if(l >= r) return true;
        int root = s[r];
        int k = l;
        while(k < r && s[k] < root) k++;
        for(int i = k;i < r;i++){
            if(s[i] < root) return false;
        }
        return dfs(l,k - 1) && dfs(k,r - 1);
    }
};